<template>
  <div class="customer-container">
    <!-- 标题和操作按钮 -->
    <div class="header">
      <div class="title">
        <el-icon><User /></el-icon>
        <h2>客户管理</h2>
      </div>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增客户
      </el-button>
    </div>
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <div class="left-section">
          <el-form-item label="客户名称">
            <el-input
                v-model="searchForm.customerName"
                placeholder="请输入客户名称"
                clearable
                prefix-icon="Search"
            />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
                v-model="searchForm.phoneNumber"
                placeholder="请输入手机号"
                clearable
                prefix-icon="Iphone"
            />
          </el-form-item>
          <el-form-item label="账户等级" class="level-select">
            <el-select
                v-model="searchForm.accountLevel"
                placeholder="请选择账户等级"
                clearable
                style="width: 160px"
            >
              <el-option label="普通会员" value="普通会员" />
              <el-option label="黄金会员" value="黄金会员" />
              <el-option label="铂金会员" value="铂金会员" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
        </div>
        <div class="right-section">
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column label="头像" width="70">
        <template #default="scope">
          <el-avatar
              :size="40"
              :src="scope.row.avatar"
          >
            <el-icon><UserFilled /></el-icon>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="loginAccount" label="登录账号" width="120" />
      <el-table-column prop="customerName" label="客户名称" width="120" />
      <el-table-column prop="phoneNumber" label="手机号码" width="120" />
      <el-table-column prop="points" label="积分" width="80" />
      <el-table-column prop="accountLevel" label="账户等级" width="100" />
      <el-table-column prop="realNameVerification" label="实名认证" width="90">
        <template #default="scope">
          <el-tag :type="scope.row.realNameVerification === '已认证' ? 'success' : 'warning'">
            {{ scope.row.realNameVerification || '未认证' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="hasChargingCard" label="充电卡" width="90">
        <template #default="scope">
          <el-tag :type="scope.row.hasChargingCard === 1 ? 'success' : 'info'">
            {{ scope.row.hasChargingCard === 1 ? '已办理' : '未办理' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isinvestor" label="投资商" width="90">
        <template #default="scope">
          <el-tag :type="scope.row.isinvestor === 1 ? 'success' : 'info'">
            {{ scope.row.isinvestor === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="showDetail(scope.row)">查看</el-button>
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="客户详情" width="500px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="头像" :span="2">
          <el-avatar
              :size="100"
              :src="currentCustomer?.avatar"
          >
            <el-icon><UserFilled /></el-icon>
          </el-avatar>
        </el-descriptions-item>
        <el-descriptions-item label="客户ID">{{ currentCustomer?.id }}</el-descriptions-item>
        <el-descriptions-item label="登录账号">{{ currentCustomer?.loginAccount }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentCustomer?.customerName }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ currentCustomer?.phoneNumber }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ currentCustomer?.gender }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ currentCustomer?.idCard }}</el-descriptions-item>
        <el-descriptions-item label="账户等级">{{ currentCustomer?.accountLevel }}</el-descriptions-item>
        <el-descriptions-item label="积分">{{ currentCustomer?.points }}</el-descriptions-item>
        <el-descriptions-item label="实名认证">{{ currentCustomer?.realNameVerification }}</el-descriptions-item>
        <el-descriptions-item label="充电卡">
          {{ currentCustomer?.hasChargingCard === 1 ? '已办理' : '未办理' }}
        </el-descriptions-item>
        <el-descriptions-item label="投资商">
          {{ currentCustomer?.isinvestor === 1 ? '是' : '否' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(currentCustomer?.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ currentCustomer?.address }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        :title="dialogType === 'add' ? '新增客户' : '编辑客户'"
        v-model="editDialogVisible"
        width="500px"
    >
      <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          style="max-height: 60vh; overflow-y: auto;"
      >
        <el-form-item label="头像">
          <div class="avatar-uploader">
            <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
            >
              <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="登录账号" prop="loginAccount">
          <el-input v-model="formData.loginAccount" placeholder="请输入登录账号" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="formData.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="账户等级" prop="accountLevel">
          <el-select v-model="formData.accountLevel" placeholder="请选择账户等级">
            <el-option label="普通会员" value="普通会员" />
            <el-option label="黄金会员" value="黄金会员" />
            <el-option label="铂金会员" value="铂金会员" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否投资商">
          <el-switch
              v-model="formData.isinvestor"
              :active-value="1"
              :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="是否有充电卡">
          <el-switch
              v-model="formData.hasChargingCard"
              :active-value="1"
              :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
              v-model="formData.address"
              type="textarea"
              placeholder="请输入地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, UserFilled ,Search, Refresh, User, Iphone } from '@element-plus/icons-vue'

// 数据定义
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const dialogType = ref('add')
const currentCustomer = ref(null)
const formRef = ref(null)

// 搜索表单
const searchForm = reactive({
  customerName: '',
  phoneNumber: '',
  accountLevel: ''
})

// 表单数据
const formData = reactive({
  id: null,
  loginAccount: '',      // 字符串
  customerName: '',      // 字符串
  phoneNumber: '',       // 字符串
  avatar: '',           // 头像URL
  isinvestor: 0,        // 数字
  points: 0,            // 数字
  hasChargingCard: 0,   // 数字
  accountLevel: '普通会员', // 字符串
  realNameVerification: '未认证', // 字符串
  gender: '',           // 字符串
  idCard: '',          // 字符串
  address: ''          // 字符串
})

// 表单验证规则
const rules = {
  loginAccount: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  accountLevel: [
    { required: true, message: '请选择账户等级', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = async (options) => {
  try {
    const uploadFormData = new FormData()
    uploadFormData.append('file', options.file)

    // 如果是编辑模式且已有头像，需要删除旧头像
    if (dialogType.value === 'edit' && formData.avatar) {
      const oldFileName = formData.avatar.split('/').pop()
      try {
        await axios.delete(`/upload/delete?fileName=${oldFileName}`)
      } catch (error) {
        console.error('删除旧头像失败:', error)
      }
    }

    // 上传新头像
    const res = await axios.post('/upload/images', uploadFormData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (res.data) {
      // res.data 已经是完整的URL，类似：http://sp6zi9loh.hn-bkt.clouddn.com/xxxxx.jpg
      formData.avatar = res.data
      ElMessage.success('头像上传成功')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取客户列表
const getCustomerList = async () => {
  try {
    const res = await axios.post('/customers/findAll', {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    })
    if (res.data) {
      tableData.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取客户列表失败:', error)
    ElMessage.error('获取客户列表失败')
  }
}

// 查看详情
const showDetail = async (row) => {
  try {
    const res = await axios.get(`/customers/find/${row.id}`)
    if (res.data) {
      currentCustomer.value = res.data
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取客户详情失败:', error)
    ElMessage.error('获取客户详情失败')
  }
}

// 新增客户
const handleAdd = () => {
  dialogType.value = 'add'
  resetFormData()
  editDialogVisible.value = true
}

// 编辑客户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, row)
  editDialogVisible.value = true
}

// 删除客户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该客户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await axios.delete(`/customers/delete/${row.id}`)
      if (res.data) {
        ElMessage.success('删除成功')
        getCustomerList()
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    avatar: '',         // 重置头像
    loginAccount: '',
    customerName: '',
    phoneNumber: '',
    isinvestor: 0,
    points: 0,
    hasChargingCard: 0,
    accountLevel: '普通会员',
    realNameVerification: '未认证',
    gender: '',
    idCard: '',
    address: ''
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          ...(dialogType.value === 'edit' ? {
            id: parseInt(formData.id) || null
          } : {}),

          // 添加头像字段
          avatar: formData.avatar,

          loginAccount: String(formData.loginAccount || '').trim(),
          customerName: String(formData.customerName || '').trim(),
          phoneNumber: String(formData.phoneNumber || '').trim(),
          gender: String(formData.gender || '').trim(),
          idCard: String(formData.idCard || '').trim(),
          address: String(formData.address || '').trim(),
          accountLevel: String(formData.accountLevel || '普通会员'),
          realNameVerification: String(formData.realNameVerification || '未认证'),
          isinvestor: Number(formData.isinvestor) || 0,
          points: Number(formData.points) || 0,
          hasChargingCard: Number(formData.hasChargingCard) || 0
        }

        let res
        if (dialogType.value === 'add') {
          res = await axios.post('/customers/add', submitData)
        } else {
          res = await axios.put('/customers/update', submitData)
        }

        if (res.data) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          editDialogVisible.value = false
          getCustomerList()
        }
      } catch (error) {
        console.error('提交失败:', error)
        const errorMessage = error.response?.data || error.message || '操作失败'
        ElMessage.error(`${dialogType.value === 'add' ? '添加' : '更新'}失败: ${errorMessage}`)
      }
    }
  })
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getCustomerList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.customerName = ''
  searchForm.phoneNumber = ''
  searchForm.accountLevel = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getCustomerList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getCustomerList()
}

// 页面加载时获取数据
onMounted(() => {
  getCustomerList()
})
</script>

<style scoped>
/* 容器基础样式 */
.customer-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);
}

/* 头部样式 */
.header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header .title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header .title h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

/* 搜索区域样式 */
.search-container {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-item-group {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  flex: 1;
}

.button-group {
  display: flex;
  gap: 8px;
  align-items: center;
  white-space: nowrap;
}

/* 表格区域样式 */
.el-table {
  margin-top: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 分页区域样式 */
.pagination {
  margin-top: 24px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 20px 24px;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #dcdfe6;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 头像上传样式 */
.avatar-uploader {
  text-align: center;
  border-radius: 8px;
  overflow: hidden;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
  border-radius: 8px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .form-item-group {
    flex-direction: column;
    width: 100%;
  }

  .button-group {
    width: 100%;
    justify-content: flex-end;
    margin-top: 16px;
  }

  :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
}

/* 通用样式调整 */
:deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 0;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
</style>